import 'dart:io';
import 'package:fate_blind_box/chat_view/dialog.dart';
import 'package:fate_blind_box/config/app_style.dart';
import 'package:fate_blind_box/config/permission_request.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:video_player/video_player.dart';
import 'actions.dart';

class MorePanel extends StatefulWidget {
  const MorePanel({Key? key, this.moreActions, this.keepDefault = true})
      : super(key: key);

  final bool keepDefault;
  final List<ActionItem>? moreActions;

  @override
  State<StatefulWidget> createState() => _MorePanelState();
}

class _MorePanelState extends State<MorePanel> {
  static const int pageSize = 8;
  final ImagePicker _picker = ImagePicker();

  List<ActionItem> getActions() {
    if (widget.moreActions != null) {
      return [
        if (widget.keepDefault) ..._defaultMoreActions(),
        ...widget.moreActions!,
      ];
    }
    return _defaultMoreActions();
  }

  List<ActionItem> _defaultMoreActions() {
    return [
      ActionItem(
          type: ActionConstants.shoot,
          icon: Image.asset(
            'images/chat/chat_camera.png',
            width: 22.w,
            height: 22.w,
          ),
          title: '拍照',
          permissions: [Permission.camera],
          onTap: _onShootActionTap),
    ];
  }

  _onShootActionTap(BuildContext context) {
    var style = TextStyle(fontSize: 16.sp, color: '333333'.stringToColor);
    showBottomChoose<int>(
            context: context,
            actions: [
              CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context, 1);
                },
                child: Text(
                  '照片',
                  style: style,
                ),
              ),
              CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context, 2);
                },
                child: Text(
                  '视频',
                  style: style,
                ),
              ),
            ],
            showCancel: true)
        .then((value) {
      if (value == 1) {
        _onTakePhoto();
      } else if (value == 2) {
        _onTakeVideo();
      }
    });
  }
  // 拍摄照片
  _onTakePhoto() async {
    // todo config image quality?
    final XFile? photo = await _picker.pickImage(
      source: ImageSource.camera,
      imageQuality: 80,
    );
    if (photo != null) {
      int len = await photo.length();
      if (kDebugMode) {
        print(len.toString());
      }
      // 发送图片
    }
  }

  // 拍摄视频
  _onTakeVideo() async {
    final XFile? video = await _picker.pickVideo(source: ImageSource.camera);
    if (video != null) {
      VideoPlayerController controller =
          VideoPlayerController.file(File(video.path));
      controller.initialize().then((value) {
          // 发送视频
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    List<ActionItem> moreActions = getActions();
    List<Widget> pages = [];
    int size = (moreActions.length / pageSize).ceil();
    for (int i = 0; i < size; ++i) {
      int start = i * pageSize;
      int end = start + pageSize > moreActions.length
          ? moreActions.length
          : start + pageSize;
      pages.add(MoreActionPage(actions: moreActions.sublist(start, end)));
    }
    return PageView(
      children: pages,
      allowImplicitScrolling: true,
    );
  }
}

class MoreActionPage extends StatelessWidget {
  const MoreActionPage({Key? key, required this.actions}) : super(key: key);

  final List<ActionItem> actions;

  @override
  Widget build(BuildContext context) {
    final sw = MediaQuery.of(context).size.width;
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: ConstrainedBox(
        constraints: const BoxConstraints.expand(),
        child: Wrap(
          spacing: (sw - 56 * 4 - 16 * 2) / 3,
          runSpacing: 16,
          children: actions.map((action) {
            return MoreItemAction(action: action);
          }).toList(),
        ),
      ),
    );
  }
}

class MoreItemAction extends StatelessWidget {
  const MoreItemAction({Key? key, required this.action}) : super(key: key);

  final ActionItem action;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        GestureDetector(
          onTap: action.permissions != null
              ? () {
                  PermissionsHelper.requestPermission(action.permissions!)
                      .then((value) {
                    if (value && action.onTap != null) {
                      action.onTap!(context);
                    }
                  });
                }
              : () {
                  if (action.onTap != null) {
                    action.onTap!(context);
                  }
                },
          child: Container(
            height: 56,
            width: 56,
            padding: const EdgeInsets.all(0),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(28), color: Colors.white),
            child: action.icon,
          ),
        ),
        const SizedBox(
          height: 4,
        ),
        Text(
          action.title ?? "",
          style:
               TextStyle(fontSize: 10.sp, color: '666666'.stringToColor),
        )
      ],
    );
  }
}
